//
//  LoginViewController.m
//  SPDBank
//
//  Created by hanxifeng on 14-12-23.
//  Copyright (c) 2014年 王 焕. All rights reserved.
//

#import "LoginViewController.h"
#import "TellerInfoViewController.h"
#import "SuggestionViewController.h"
#import "MenuViewController.h"
#import "SuggestionViewController.h"
#import "SliderViewController.h"
@interface LoginViewController ()

@end

@implementation LoginViewController{
    UITextField *_accountField;//工号
    UITextField *_passwordField;//密码
    UIButton *_rememberPwdBtn;//记住密码按钮
    UIButton *_autoLoginBtn;//自动登陆按钮
    UIAlertView *_alertView;//弹出信息
    NSMutableDictionary *_dataDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataDic = [[NSMutableDictionary alloc]init];
    //搭建界面
    [self buildUI];
}

#pragma mark 搭建界面
-(void)buildUI{
    //背景图
    self.view.backgroundColor = [UIColor colorWithPatternImage:IMG(@"LoginBack")];
    //白色背景view
    CGFloat paddingX = 197.5/2;
    CGFloat paddingY = 470/2;
    CGFloat width = WIDTH - 2*paddingX;
    CGFloat heigh = 300;
    UIView *whiteBackView = [[UIView alloc]initWithFrame:CGRectMake(paddingX, paddingY, width, heigh)];
    whiteBackView.backgroundColor = [UIColor colorWithPatternImage:IMG(@"WhiteBack")];
    [self.view addSubview:whiteBackView];
    //账号
    CGFloat imageSize = 20;
    CGFloat accountPaddingY = 100;
    UIImageView *accountView = [[UIImageView alloc]initWithFrame:CGRectMake(50, accountPaddingY, imageSize, imageSize)];
    accountView.image = IMG(@"a");
    [whiteBackView addSubview:accountView];
    UILabel *accountLable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(accountView.frame)+5, accountPaddingY, 70, imageSize)];
    accountLable.text = @"工 号：";
    accountLable.font = [UIFont systemFontOfSize:20];
    [whiteBackView addSubview:accountLable];
    //账号field
    _accountField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(accountLable.frame), accountPaddingY-5, 200, 30)];
    _accountField.background = IMG(@"loginc");
    [whiteBackView addSubview:_accountField];
    
    
    //密码
    CGFloat paddingOne = 30;//距离上面的账号的距离
    UIImageView *passwordView = [[UIImageView alloc]initWithFrame:CGRectMake(50, CGRectGetMaxY(accountView.frame)+paddingOne, imageSize, imageSize)];
    passwordView.image = IMG(@"p");
    [whiteBackView addSubview:passwordView];
    UILabel *passwordLable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(passwordView.frame)+5, CGRectGetMaxY(accountLable.frame)+paddingOne, 70, imageSize)];
    passwordLable.text = @"密 码：";
    passwordLable.font = [UIFont systemFontOfSize:20];
    [whiteBackView addSubview:passwordLable];
    //密码field
    _passwordField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(accountLable.frame), CGRectGetMaxY(_accountField.frame)+paddingOne-5,200, 30)];
    _passwordField.secureTextEntry = YES;
    _passwordField.background = IMG(@"loginc");
    [whiteBackView addSubview:_passwordField];
    
    
    //记住密码
    CGFloat paddingTwo = 50;//距离上面的密码的距离
    _rememberPwdBtn = [[UIButton alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(passwordLable.frame)+paddingTwo, 150, 20)];
    [_rememberPwdBtn setTitle:@"  记住密码" forState:UIControlStateNormal];
    [_rememberPwdBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_rememberPwdBtn setImage:IMG(@"uncheck") forState:UIControlStateNormal];
    [_rememberPwdBtn setImage:IMG(@"check") forState:UIControlStateSelected];
    [_rememberPwdBtn addTarget:self action:@selector(btnAct:) forControlEvents:UIControlEventTouchUpInside];
    [whiteBackView addSubview:_rememberPwdBtn];
    
    //自动登陆
    _autoLoginBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_rememberPwdBtn.frame)+40, CGRectGetMaxY(passwordLable.frame)+paddingTwo, 150, 20)];
    [_autoLoginBtn setTitle:@"  自动登陆" forState:UIControlStateNormal];
    [_autoLoginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_autoLoginBtn setImage:IMG(@"uncheck") forState:UIControlStateNormal];
    [_autoLoginBtn setImage:IMG(@"check") forState:UIControlStateSelected];
    [_autoLoginBtn addTarget:self action:@selector(btnAct:) forControlEvents:UIControlEventTouchUpInside];
    [whiteBackView addSubview:_autoLoginBtn];
    
    //登陆按钮
    CGFloat btnSize = 100;
    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_passwordField.frame)+250, (whiteBackView.frame.size.height - btnSize)/2, btnSize, btnSize)];
    loginBtn.backgroundColor = [UIColor orangeColor];
    [loginBtn addTarget:self action:@selector(loginAct) forControlEvents:UIControlEventTouchUpInside];
    [whiteBackView addSubview:loginBtn];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"remeberPwd"]==[NSNumber numberWithBool:YES]) {//yes 选中密码
        _rememberPwdBtn.selected = YES;
        _accountField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        _passwordField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userPwd"];
    }
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"]==[NSNumber numberWithBool:YES]) {//yes 自动登陆的话记住密码也必须选中
        _autoLoginBtn.selected = YES;
        _rememberPwdBtn.selected = YES;
        _accountField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        _passwordField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userPwd"];
        [self loginAct];
    }
}

#pragma mark 登陆action
-(void)loginAct{
    //跳转到slider
    [self goToSliderViewController];

    //判断是否为空
//    if ([_accountField.text isEqualToString:@""]||[_passwordField.text isEqualToString:@""]) {
//        _alertView = [[UIAlertView alloc]initWithTitle:nil message:@"账户信息不能为空！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [_alertView show];
//        return;
//    }
//     [SVProgressHUD showWithStatus:@"登陆中.." maskType:SVProgressHUDMaskTypeBlack];
////    发送请求
//    NSURL *loginUrl = [[NSURL alloc]initWithString:HTTP_LOGIN];
//    ASIFormDataRequest *request = [[ASIFormDataRequest alloc]initWithURL:loginUrl];
//    request.delegate = self;
//    [request setPostValue:_accountField.text forKey:@"uid"];
//    [request setPostValue:_passwordField.text forKey:@"passwd"];
//    [request setDidFinishSelector:@selector(httpFinish:)];
//    [request setDidFailSelector:@selector(httpFail:)];
//    [request startAsynchronous];
}
//成功
-(void)httpFinish:(ASIFormDataRequest *)request{
    [SVProgressHUD dismiss];
    if (![request error]) {//没有错误
        //取出data类型的数据
        NSData *jsonData = [request responseData];
        //根据utf-8编码转成字符串形式
        NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
        //转成json
        NSMutableDictionary *kitData = [jsonString objectFromJSONString];
        //赋值给成员变量
        _dataDic = kitData;
        //判断账号信息是否验证成功
        NSString *flag = [NSString stringWithFormat:@"%@",[kitData objectForKey:@"recode"]];
        if ([flag isEqualToString:@"0"]) {//成功
            [SVProgressHUD showSuccessWithStatus:@"登陆成功！"];
            if (_rememberPwdBtn.selected) {//选中记住密码 存入沙盒 yes是1 可以进入if
                [[NSUserDefaults standardUserDefaults]setObject:_accountField.text forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults]setObject:_passwordField.text forKey:@"userPwd"];
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:@"remeberPwd"];//yes是1 no是0
            }else{
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:NO] forKey:@"remeberPwd"];
                NSLog(@"======没记住==%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"remeberPwd"]);
            }
            if (_autoLoginBtn.selected) {//选中自动登陆 存入沙盒
                [[NSUserDefaults standardUserDefaults]setObject:_accountField.text forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults]setObject:_passwordField.text forKey:@"userPwd"];
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:YES] forKey:@"autoLogin"];//yes是1 no是0
                 NSLog(@"=======自动=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"]);
            }else{
                [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithBool:NO] forKey:@"autoLogin"];
                 NSLog(@"=======不自动=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"]);
            }
            //跳转到slider
            [self goToSliderViewController];
        }else if([flag isEqualToString:@"1"]){//失败
            _alertView = [[UIAlertView alloc]initWithTitle:nil message:[kitData objectForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [_alertView show];
            return;
        }
    }else{
        [SVProgressHUD showErrorWithStatus:@"请检查您的网络！"];
    }
}
//失败
-(void)httpFail:(ASIFormDataRequest *)request{
    NSError *error = [request error];
    if (error.code == ASIRequestTimedOutErrorType) {
        [SVProgressHUD showErrorWithStatus:@"网络请求超时！"];
    }else if (error.code == ASIRequestCancelledErrorType){
        [SVProgressHUD showErrorWithStatus:@"网络请求失败！"];
    }
    NSLog(@"Connection faild! Error - %@ %@",[error localizedDescription],[[error userInfo]objectForKey:NSURLErrorFailingURLErrorKey]);
}
-(void)goToSliderViewController{
    //跳转到slider
    SliderViewController *sliderViewController = [[SliderViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:sliderViewController];
    sliderViewController.dataDic = _dataDic;
    [self presentViewController:nav animated:YES completion:nil];
}
#pragma mark 记住密码自动登陆点击
-(void)btnAct:(UIButton *)btn{
    btn.selected = !btn.selected;
}
//失去焦点
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_accountField resignFirstResponder];
    [_passwordField resignFirstResponder];
}
@end
